package jwm.network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

import jwm.event.Dispatcher;
import jwm.event.Event;
import jwm.event.EventDispatcher;
import jwm.event.EventListener;
import jwm.event.ExceptionEvent;
import jwm.event.URLLoaderEvent;

public class ThreadLoader extends Thread implements Dispatcher {

   private BufferedReader reader;
   private StringBuffer file;
   private EventDispatcher eventDispatcher;
   
   public ThreadLoader() {
      eventDispatcher = new EventDispatcher();
   }
   
   public void load(URL url) {
      file = new StringBuffer();
      try {
         reader = new BufferedReader(new InputStreamReader(url.openStream()));
      } catch (IOException e) {
         close();
         dispatchEvent(new ExceptionEvent());
      }
      start();
   }
   
   @Override
   public void run() {
      String inputLine;
      try {
         while ((inputLine = reader.readLine()) != null) {
            file.append(inputLine);
         }
      } catch (IOException e) {
         close();
         dispatchEvent(new ExceptionEvent());
      }
      dispatchEvent(new URLLoaderEvent(file.toString()));
   }

   @Override
   public void dispatchEvent(Event event) {
      eventDispatcher.dispatchEvent(event);
   }

   @Override
   public void addEventListener(EventListener listener) {
      eventDispatcher.addEventListener(listener);
   }

   @Override
   public void removeEventListener(Object listener) {
      eventDispatcher.removeEventListener(listener);
   }

   public void close() {
      try {
         reader.close();
      } catch (IOException e) {}
   }

}
